import collections
class Solution(object):
    def watchedVideosByFriends(self, watchedVideos, friends, id, level):
        n = len(friends)
        d = collections.defaultdict(list)
        for index, f in enumerate(friends):
            d[index] += f
        used = [0] * n
        used[id] = 1
        now_set = {id}
        dist = 0
        while now_set and dist < level:
            next_set = set()
            dist += 1
            for node in now_set:
                for v in d[node]:
                    if not used[v]:
                        used[v] = 1
                        next_set.add(v)
            now_set = next_set
        if dist == level and now_set:
            w = collections.defaultdict(int)
            for node in now_set:
                for t in watchedVideos[node]:
                    w[t] += 1
            w = [[w[key], key] for key in w]
            w.sort()
            return [t[1] for t in w]
        else:
            return []


